﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.DataAccess.Trademark.Interfaces;
using AMS.DataAccess.Trademark.BO;
using AMS.DataAccess;
using AMS.DataAccess.Trademark.Filters;
using AMS.DataAccess.Filter;

public partial class Task_GenerateTask : BaseWorkPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DoDataBind();
            SelectFirstRecvFile();
        }
        else
        {
            LoadTaskList(TaskCount, null);
        }
    }

    #region Private Fields
    int recordCount;
    int taskCount = 0;
    int TaskCount
    {
        get { return ViewState["TaskCount"] == null ? 0 : (int)ViewState["TaskCount"]; }
        set { ViewState["TaskCount"] = value; }
    }

    int SelectedRFID
    {
        get { return ViewState["SelectedRFID"] == null ? 0 : (int)ViewState["SelectedRFID"]; }
        set { ViewState["SelectedRFID"] = value; }
    }
    #endregion

    protected string GetDisplayName(object caseIndex, object caseName)
    {
        if (caseIndex == null || caseIndex == DBNull.Value)
        {
            return "(无案件号) " + caseName.ToString();
        }
        else
        {
            return "(" + caseIndex.ToString() + ") " + caseName.ToString();
        }
    }

    void DoDataBind()
    {
        IRecvFileManager rfMgr = ManagerFactory.CreateRecvFileManager();
        List<RecvFileInfo> rfList = rfMgr.GetNewRecvFiles(CallContext);
        repRF.DataSource = rfList;
        repRF.DataBind();
        recordCount = rfList.Count;
    }

    void SelectFirstRecvFile()
    {
        if (repRF.Items.Count > 0)
        {
            LinkButton lk = repRF.Items[0].FindControl("lk") as LinkButton;
            lkRFChanged_Command(lk, new CommandEventArgs(null, lk.CommandArgument));
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="count"></param>
    /// <param name="tasks">NULL means do not bind data</param>
    void LoadTaskList(int count, List<RFTaskInfo> tasks)
    {
        if (count < TaskCount)
        {
            for (int i = TaskCount - 1; i >= count; i--)
            {
                phCtrls.Controls.RemoveAt(i);
            }
        }

        if (tasks == null)
        {
            for (int i = 0; i < count; i++)
            {
                Control ctrl = LoadControl("~/Task/ucTaskDetail.ascx");
                ITaskEditCtrl taskEditCtrl = ctrl as ITaskEditCtrl;
                taskEditCtrl.IsInTaskGeneration = true;
                phCtrls.Controls.Add(ctrl);
            }
        }
        else
        {
            int ctrlCount = phCtrls.Controls.Count;
            for (int i = 0; i < ctrlCount; i++)
            {
                Control ctrl = phCtrls.Controls[i];
                ITaskEditCtrl taskEditCtrl = ctrl as ITaskEditCtrl;
                taskEditCtrl.IsInTaskGeneration = true;
                taskEditCtrl.InitialControl(tasks[i]);
            }

            for (int i = ctrlCount; i < count; i++)
            {
                Control ctrl = LoadControl("~/Task/ucTaskDetail.ascx");
                phCtrls.Controls.Add(ctrl);
                ITaskEditCtrl taskEditCtrl = ctrl as ITaskEditCtrl;
                taskEditCtrl.IsInTaskGeneration = true;
                taskEditCtrl.InitialControl(tasks[i]);
            }
        }
    }

    protected void lkRFChanged_Command(object sender, CommandEventArgs e)
    {
        string said = e.CommandArgument.ToString();
        LinkButton ctrl = sender as LinkButton;
        int []ids = ExtractIDs(said);
        int aid = ids[0];
        ChangeLinkStyle(ctrl, ids[1]);

        IRecvFileManager rfMgr = ManagerFactory.CreateRecvFileManager();
        RFTaskFilter filter = new RFTaskFilter();
        filter.RecvFileID = new IntegerFilterField(aid);
        List<RFTaskInfo> tasks = rfMgr.GetRFTask(CallContext, filter);

        taskCount = tasks.Count;
        // phCtrls.Controls.Clear();
        LoadTaskList(taskCount, tasks);

        TaskCount = taskCount;
        SelectedRFID = aid;
    }

    int[] ExtractIDs(string sid)
    {
        string[] slist = sid.Split(',');
        int[] ids = new int[2];
        ids[0] = int.Parse(slist[0]);
        ids[1] = int.Parse(slist[1]);
        return ids;
    }

    void ChangeLinkStyle(LinkButton lk, int selectedIndex)
    {
        if (ViewState["LastSelected"] != null)
        {
            int lastSelectedIndex = (int)ViewState["LastSelected"];
            if (lastSelectedIndex >= 0 && lastSelectedIndex < repRF.Items.Count)
            {
                LinkButton lk2 = repRF.Items[lastSelectedIndex].FindControl("lk") as LinkButton;
                if (lk2 != null)
                {
                    lk2.Attributes["class"] = "";
                }
            }
        }
        lk.Attributes["class"] = "selectedLink";
        ViewState["LastSelected"] = selectedIndex;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        List<ITaskEditCtrl> taskEditCtrls = new List<ITaskEditCtrl>();
        for (int i = 0; i < phCtrls.Controls.Count; i++)
        {
            ITaskEditCtrl taskEditCtrl = phCtrls.Controls[i] as ITaskEditCtrl;
            if (taskEditCtrl != null)
            {
                taskEditCtrls.Add(taskEditCtrl);
            }
        }

        List<TaskInfo> tasks = new List<TaskInfo>();
        for (int i = 0; i < taskEditCtrls.Count; i++)
        {
            if (taskEditCtrls[i].EnableGenerateTask)
            {
                TaskInfo task = new TaskInfo();
                if (!taskEditCtrls[i].GetTask(task))
                {
                    MsgInfo(" 验证出错");
                    return;
                }
                else
                {
                    // TODO: fill default values here
                    tasks.Add(task);
                }
            }
        }

        if (tasks.Count > 0)
        {
            ITaskManager taskMgr = ManagerFactory.CreateTaskManager();
            taskMgr.BatchAddTasks(CallContext, tasks);
            MsgInfo("生成任务成功！");
        }
        else
        {
            MsgWarning("未生成任何任务。");
            //return;
        }

        IRecvFileManager rfMgr = ManagerFactory.CreateRecvFileManager();
        rfMgr.SetRFAlreadyGenerateTaskFlag(CallContext, SelectedRFID);
        DoDataBind();
        SelectFirstRecvFile();
    }

    protected void btnTest_Click(object sender, EventArgs e)
    {
        
    }
}

